/*
 * File     : NativeCallFactory.java
 * Created  : 22 Apr 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.call;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.objectweb.asm.ClassWriter;

import com.googlecode.dni.type.Pointer;
import com.googlecode.dni.type.nativetype.NativeChar;
import com.googlecode.dni.type.nativetype.NativeInt;
import com.googlecode.dni.type.nativetype.NativeLong;
import com.googlecode.dni.type.nativetype.NativeShort;
import com.googlecode.dni.type.nativetype.NativeTypes;
import com.googlecode.dni.type.nativetype.SizeT;
import com.googlecode.dni.type.nativetype.WCharT;


/**
 * <p>
 *  Encapsulates the logic to generate the native call methods.
 * </p>
 *
 * @author Matthew Wilson
 */
public abstract class NativeCallFactory
{

    /**
     * Map of primitive types to their signature value.
     */
    static final Map< Class< ? >, Character > NATIVE_SIGNATURES =
        new HashMap< Class< ? >, Character >();

    /**
     * Map of natively sized types to their Java primitive type.
     */
    static final Map< Class< ? >, Class< ? > > NATIVE_TYPES =
        new HashMap< Class< ? >, Class< ? > >();

    static
    {
        NATIVE_SIGNATURES.put( void.class,    'V' );
        NATIVE_SIGNATURES.put( boolean.class, 'Z' );
        NATIVE_SIGNATURES.put( byte.class,    'B' );
        NATIVE_SIGNATURES.put( short.class,   'S' );
        NATIVE_SIGNATURES.put( char.class,    'C' );
        NATIVE_SIGNATURES.put( int.class,     'I' );
        NATIVE_SIGNATURES.put( long.class,    'J' );
        NATIVE_SIGNATURES.put( float.class,   'F' );
        NATIVE_SIGNATURES.put( double.class,  'D' );

        put( NativeChar.class,  int.class,  NativeTypes.NATIVE_CHAR_SIZE );
        put( NativeShort.class, int.class,  NativeTypes.NATIVE_SHORT_SIZE );
        put( NativeInt.class,   int.class,  NativeTypes.NATIVE_INT_SIZE );
        put( NativeLong.class,  long.class, NativeTypes.NATIVE_LONG_SIZE );
        put( SizeT.class,       long.class, NativeTypes.SIZE_T_SIZE );
        put( WCharT.class,      int.class,  NativeTypes.W_CHAR_T_SIZE );
    }


    private Class< ? > type;

    private ClassWriter classWriter;

    private String implName;

    private String nativePrefix;

    private int nativeIndex;


    /**
     * @param type
     *            the library type
     * @param classWriter
     *            the class writer
     * @param implName
     *            the implementation name
     */
    @SuppressWarnings( "hiding" )
    public void init( final Class< ? > type,
                      final ClassWriter classWriter,
                      final String implName )
    {
        this.type = type;
        this.classWriter = classWriter;
        this.implName = implName;

        boolean bad = true;
        this.nativePrefix = "_native_";
        while ( bad )
        {
            bad = false;
            for ( Method method : type.getMethods() )
            {
                if ( method.getName().startsWith( this.nativePrefix ) )
                {
                    bad = true;
                    this.nativePrefix += "_";
                }
            }
        }
    }

    /**
     * Writes a Java method with a corresponding native method.
     *
     * @param method
     *            the Java method
     * @param functionPointer
     *            the function pointer of the native method
     * @param charset
     *            the charset for the function
     *
     * @return the native method created (to be registered)
     */
    public abstract JniNativeMethod writeMethod( Method method,
                                                 Pointer functionPointer,
                                                 String charset );

    /**
     * Writes a Java static initaliser for the class, if one is necessary.
     */
    public abstract void writeStaticInitialiser();

    /**
     * @return the library type
     */
    final Class< ? > getType()
    {
        return this.type;
    }

    /**
     * @return the class writer
     */
    final ClassWriter getClassWriter()
    {
        return this.classWriter;
    }

    /**
     * @return the implementation type name
     */
    final String getImplName()
    {
        return this.implName;
    }

    /**
     * @return a unique native method name
     */
    final String generateNativeMethodName()
    {
        this.nativeIndex++;
        return this.nativePrefix + this.nativeIndex;
    }

    private static void put( final Class< ? extends Annotation > type,
                             final Class< ? > javaType,
                             final int size )
    {
        char sig;

        switch ( size )
        {
            case 1:
                sig = 'B';
                break;

            case 2:
                sig = 'S';
                break;

            case 4:
                sig = 'I';
                break;

            case 8:
                sig = 'J';
                break;

            default:
                throw new AssertionError( "Unsupported size: " + type + " " + size );
        }

        NATIVE_SIGNATURES.put( type, sig );

        NATIVE_TYPES.put( type, javaType );
    }

}
